# -*- coding: utf-8 -*-

import functools
import json

import tornado.web

from apps.utils import JsonEncoder, Utils


def requires_auth(func):
    @functools.wraps(func)
    async def wrapper(self, *args, **kwargs):
        access_token = self.request.headers.get('access-token')
        # 分割解密出用户id
        user_id = Utils.aes().decrypt(access_token.split('-')[1])
        if user_id and access_token:
            # 通过用户ID获得缓存用户信息
            cuser = self.cache_action.token().get(str(user_id))
            if cuser:
                cuser = json.loads(cuser)
            else:
                cuser = None
                return self.render_json(900, '用户信息查询失败! 请重新登录！')
            # 检查数据是否一致
            if user_id != cuser.get('id') and access_token != cuser.get(
                    'token'):
                return self.render_json(900, '您已退出!')
        else:
            return self.render_json(900, '请求参数不全')
        await func(self, cuser, *args, **kwargs)

    return wrapper


def is_ruaptcha(func):
    @functools.wraps(func)
    async def wrapper(self, *args, **kwargs):
        t = self.get_argument('t', default='')
        validate = self.get_argument('validate', default='')
        if Utils.is_null(t) and Utils.is_null(validate):
            return self.render_json(-1, '请求参数错误')
        ruaptcha = self.cache_action.ruaptcha().get(t)
        if validate.lower() != ruaptcha:
            return self.render_json(-1, '验证码错误')
        await func(self, *args, **kwargs)

    return wrapper


class BaseHandler(tornado.web.RequestHandler):
    def head_json(self):
        self.set_header('Content-type', 'application/json;charset=utf-8')

    def render_json(self, code=-1, msg='', data=None):
        d = dict()
        d['code'] = code
        d['msg'] = msg
        if data:
            d['data'] = data
        else:
            d['data'] = ''
        self.head_json()
        self.write(json.dumps(d, cls=JsonEncoder))

    def initialize(self):
        pass

    @property
    def cache_action(self):
        return self.application.cache_action

    @property
    def user_model(self):
        return self.application.user_model

    @property
    def device_model(self):
        return self.application.device_model

    @property
    def alarm_model(self):
        return self.application.alarm_model

    # 配置头信息允许跨域访问
    def set_default_headers(self):
        self.set_header('Access-Control-Allow-Origin', '*')
        self.set_header(
            'Access-Control-Allow-Headers',
            'Origin, X-Requested-With, Content-Type, Accept, access-token, Authorization'
        )
        self.set_header('Access-Control-Allow-Methods', 'POST, GET, OPTIONS')
        # self.set_header('Access-Control-Max-Age', 1000)

    def options(self):
        pass

    # 处理常见错误类型，输出JSON提示
    def write_error(self, status_code, **kwargs):
        if status_code == 404:
            code, msg = (404, '404 没有找到地址')
        elif status_code == 405:
            code, msg = (405, '405 方法不允许')
        elif status_code == 500:
            code, msg = (500, '500 服务器内部错误')
        else:
            code, msg = (status_code, 'unknown error')
        return self.render_json(code, msg)

    def get_current_user(self):
        user_id = self.request.headers.get('user-id')
        access_token = self.request.headers.get('access-token')
        result = None
        token_cache = json.loads(
            self.cache_action.token().get(user_id))
        if access_token == token_cache['token']:
            result = token_cache
        return result

    def get_user_by_id(self, userid):
        return json.loads(self.cache_action.token().get(userid))
